/*****************************************************************************************
 **  Author:COCO 2022
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
// import gridHeader from '../production/production_extend/Production_InventoryNeedGridHeader'
import { defineAsyncComponent } from 'vue'
let extension = {
  components: {
    //查询界面扩展组件
    gridHeader: defineAsyncComponent(() =>
      import(
        '../production/production_extend/Production_InventoryNeedGridHeader'
      )
    ),
    gridBody: '',
    gridFooter: defineAsyncComponent(() =>
      import(
        '../production/production_extend/Production_InventoryNeedGridFooter'
      )
    ),
    //新建、编辑弹出框扩展组件
    modelHeader: '',
    modelBody: '',
    modelFooter: '',
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: {
    view: [],
    box: [],
    detail: [],
  }, //扩展的按钮
  methods: {
    //下面这些方法可以保留也可以删除
    async onInit() {
      //框架初始化配置前，
      //示例：在按钮的最前面添加一个按钮
      //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
      //     name: '按钮', //按钮名称
      //     icon: 'el-icon-document', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
      //     type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
      //     onClick: function () {
      //       this.$Message.success('点击了按钮');
      //     }
      //   });

      //示例：设置修改新建、编辑弹出框字段标签的长度
      // this.boxOptions.labelWidth = 150;
      //显示序号(默认隐藏)
      let { permission } = this.$store.getters.getPermission(
        '/Production_InventoryNeed'
      )

      this.columnIndex = true
      if (permission.includes('createInvNeedOrder')) {
        this.buttons.push({
          name: '开领料单',
          icon: 'el-icon-document',
          type: 'warning',
          onClick: async () => {
            try {
              let selectedList = this.$refs.table.getSelected()
              let MoCodeArr = []
              let WoCodeArr = []
              // console.log(selectedList)
              if (selectedList.length == 0) {
                this.$message.warning('请选择开具领料单的数据')
                return
              }

              let addOutRawMaterial = selectedList.map((item) => {
                if (item.Status == 1) {
                  throw new Error('请选择未开具领料单的物料信息')
                }
                if (!MoCodeArr.includes(item.MoCode))
                  MoCodeArr.push(item.MoCode)
                if (!WoCodeArr.includes(item.WoCode))
                  WoCodeArr.push(item.WoCode)
                let {
                  MoCode: orderNum,
                  InvName: productName,
                  InvCode: productCode,
                  InvStd: specification,
                  ProCode: type,
                  Qty: qnty,
                  CreateUserId: createID,
                  IType: iType,
                  Id: RequisitionID,
                  WoCode,
                  Unit,
                } = item

                return {
                  outRawMaterialID: 0,
                  postID: '',
                  outQnty: 0,
                  lotNo: '',
                  state: 0,
                  creator: '',
                  modifier: '',
                  modifyID: 0,
                  orderNum,
                  productName,
                  specification,
                  type,
                  qnty,
                  createID,
                  iType,
                  RequisitionID,
                  productCode,
                  WoCode,
                  Unit,
                }
              })

              if (MoCodeArr.length > 1)
                return this.$message.error('请选择同一订单下的物料')
              if (WoCodeArr.length > 1)
                return this.$message.error('请选择同一工单下的物料')
              let res = await this.http.get(
                `/api/Production_WorkOrder/GetMoCodeDetail?MoCode=${MoCodeArr[0]}&WoCode=${WoCodeArr[0]}`,
                null,
                true
              )
              // console.log(res);
              this.$refs.gridHeader.open(
                addOutRawMaterial,
                this.print,
                res,
                '开具领料单'
              )
            } catch (err) {
              this.$message.warning(err.message)
            }
          },
        })
      }

      if (permission.includes('overGet')) {
        this.buttons.push({
          name: '超领申请',
          icon: 'el-icon-s-claim',
          type: 'danger',
          onClick: () => {
            this.$refs.gridFooter.open()
          },
        })
      }

      if (permission.includes('createOverGet')) {
        this.buttons.push({
          name: '开超领单',
          icon: 'el-icon-document',
          type: 'success',
          onClick: async () => {
            let selectList = this.$refs.table.getSelected()
            if (selectList.length === 0)
              return this.$message.error('请选择数据')
            let woCodeArr = new Set()

            try {
              let mapList = selectList.map((item) => {
                let {
                  MoCode: orderNum,
                  InvName: productName,
                  InvCode: productCode,
                  InvStd: specification,
                  ProCode: type,
                  Qty: qnty,
                  CreateUserId: createID,
                  IType: iType,
                  Id: RequisitionID,
                  WoCode,
                } = item
                if (item.Status == 1)
                  throw new Error('请选择未开具超领单的物料信息')
                if (type !== '补料')
                  throw new Error('选择的单据中有不是通过超领生成的物料需求单')

                woCodeArr.add(item.WoCode)
                return {
                  outRawMaterialID: 0,
                  postID: '',
                  outQnty: 0,
                  lotNo: '',
                  state: 0,
                  creator: '',
                  modifier: '',
                  modifyID: 0,
                  orderNum,
                  productName,
                  specification,
                  type,
                  qnty,
                  createID,
                  iType,
                  RequisitionID,
                  productCode,
                  WoCode,
                }
              })

              if (woCodeArr.size > 1)
                return this.$message.error('选中的单据中包含多个工单')
              let res = await this.http.get(
                `/api/Production_WorkOrder/GetMoCodeDetail?MoCode=${selectList[0].MoCode}&WoCode=${selectList[0].WoCode}`,
                null,
                true
              )
              this.$refs.gridHeader.open(mapList, this.print, res, '开具超领单')
            } catch (error) {
              this.$message.error(error.message)
            }
          },
        })
      }
    },
    onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
    },
    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      return true
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return true
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      // this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=='Add';
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段='xxx';
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
    },
    print(data, PrintTitle) {
      console.log(data)
      let printWindow = window.open('', '_blank')
      printWindow.document.open()
      let style = `<style>
                      .title {
                        text-align:center;
                        position: relative;
                      }

                      .header {
                        display: flex;
                        margin-bottom: 20px;
                      }

                      .t_head {
                        flex: 1;
                      }

                      .t_head .th_item {
                        display: flex; 
                        list-style: none;
                      }

                      .t_head .th_item .th_title {
                        flex: 1; 
                        display: flex;
                        text-align: left;
                        text-indent: 20;
                      }

                      .th_title .th_title_space {
                        display: inline-block; 
                      }

                      #qrcodeImg {
                        width: 100px; 
                        height: 100px;
                        margin-left: 10px;
                      }

                      .grid_table {
                        width: 100%; 
                        border: 1px solid #000; 
                        border-collapse: collapse;
                      }

                      th {
                        border: 1px solid black;  
                      }

                      .grid_table tr td {
                        border: 1px solid black;
                      }

                      .grid_table tbody {
                        text-align:center;
                      }

                      .footer {
                        display: flex; 
                        justify-content: 
                        space-between; 
                        list-style: none;
                      }

                      .footer_space {
                        margin-left: 30px;
                        display: inline-block; 
                        width: 150px; 
                        border-bottom: 1px solid #000;
                      }

                      .version {
                        margin-top: 15px;
                      }
                    </style>`

      let title = `<div>
                        <h1 class="title">昆山鸿永峻精密五金电子科技有限公司</h1>
                        <h1 class="title">${PrintTitle}</h1>
                    </div>`

      // let header = `<div class="header">
      //                   <div class="t_head">
      //                     <ul class="th_item">
      //                       <li class="th_title">
      //                         客户名称:
      //                         <span class="th_title_space" style="margin-left: 5px;">${CusName}</span>
      //                       </li>

      //                       <li class="th_title">
      //                         地址:
      //                         <span class="th_title_space" style="margin-left: 5px;">昆山市周市镇青阳北路565号</span>
      //                       </li>
      //                     </ul>

      //                     <ul class="th_item">
      //                       <li class="th_title">
      //                         送货日期:
      //                         <span class="th_title_space" style="margin-left: 5px;">2023-11-16</span>
      //                       </li>
      //                       <li class="th_title">
      //                         电话/传真:
      //                         <span class="th_title_space" style="margin-left: 5px;">0512-57905229</span>
      //                       </li>
      //                     </ul>
      //                   </div>

      //                   <div id="qrcodeImg"></div>
      //               </div>`

      let footer = `
                  <div>
                    <ul class="footer"> 
                        <li>
                          审核:
                          <span class="footer_space"></span>
                        </li>
                        <li>
                          核准:
                          <span class="footer_space"></span>
                        </li>
                    </ul>
                  <div>`

      // let result = chunkArray(data.deliveryDetail, 24)
      let result = [data.detailData]
      // console.log(result)
      let body = ``
      result.forEach((arr) => {
        let main = ``
        arr.forEach((item, index) => {
          main += `
        <tr style="border: 1px dotted black;">
          <td colspan="2">${item.productName}</td>
          <td colspan="2">${item.productCode}</td>
          <td>${item.specification}</td>
          <td>${item.Unit}</td>
          <td>${item.qnty}</td>
        </tr>`
        })

        body += `<table class="grid_table">
          <thead>
            <tr>
              <th>产品名称</th>
              <th>${data.mainData.productName}</th>
              <th>产品编码</th>
              <th>${data.mainData.productCode}</th>
              <th>制表日期</th>
              <th>${data.mainData.createDate}</th>
            </tr>
            <tr>
              <th>工单数量</th>
              <th>${data.mainData.qty}</th>
              <th>损耗</th>
              <th>${data.mainData.loss}</th>
              <th>毛重</th>
              <th>${data.mainData.grossWeight}</th>
              
            </tr>
            <tr>
              <th>单重</th>
              <th>${data.mainData.singleWeight}</th>
              <th>领料人</th>
              <th>${data.mainData.userName}</th>
              <th>发料人</th>
              <th>${data.mainData.senderName}</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td colspan="8">物料信息</td>
            </tr>
            <tr>
              <td colspan="2">物料名称</td>
              <td colspan="2">物料编码</td>
              <td>规格</td>
              <td>单位</td>
              <td>数量</td>
            </tr>
            ${main}
            <tr>
              <td colspan="6">注：本单作为领料依据，敬请妥善保管。</td>
            </tr>
          </tbody>
        </table>${footer}`
      })

      // let sscript = ` <script src="/qrcode.min.js" type="application/javascript"></script>
      //                 <script>
      //                   window.addEventListener("DOMContentLoaded", ()=> {
      //                     const qrcodeImgEl = document.getElementById('qrcodeImg')
      //                     qrcodeImgEl.innerHTML = ''
      //                     let qrcode = new QRCode(qrcodeImgEl, {
      //                                             width: 100,
      //                                             height: 100,
      //                                             colorDark: '#000000',
      //                                             colorLight: '#ffffff',
      //                                             correctLevel: QRCode.CorrectLevel.H,
      //                                   })
      //                     qrcode.makeCode('${deliveryOrderCode}')
      //                   })
      //                 </script>`
      printWindow.document.write(
        `<html><head><title>Print</title>${style}</head><body>`
      )
      printWindow.document.write(title)
      // printWindow.document.write(header)
      printWindow.document.write(body)
      printWindow.document.write(`</body></html>`)
      printWindow.document.close()
      setTimeout(() => {
        printWindow.print()
        printWindow.close()
      }, 100)
    },
  },
}
export default extension
